<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px" v-show="showSearch">
            <el-form-item label="震级" prop="dedEarthquake">
                <el-input v-model="queryParams.dedEarthquake" placeholder="请输入震级" clearable />
            </el-form-item>
            <el-form-item label="地震事件简称" prop="dedName">
                <el-input v-model="queryParams.dedName" placeholder="请输入地震事件简称" clearable />
            </el-form-item>
            <el-form-item label="震中(宏观)" prop="dedMacroscopicEpicenter">
                <el-input v-model="queryParams.dedMacroscopicEpicenter" placeholder="请输入震中(宏观)" clearable />
            </el-form-item>
            <el-form-item label="发生时刻" prop="time">
                <el-date-picker clearable v-model="queryParams.time" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button plain @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="Plus" @click="handleAdd">添加</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button plain icon="Download" @click="handleImport">导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button plain icon="Edit" :disabled="dataList.length==0" @click="handleExport">导出</el-button>
            </el-col>
            <el-col :span="1.5" v-if="isAdminShow">
                <el-button plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="dataList" stripe @selection-change="handleSelectionChange" row-key="dedId">
            <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
            <el-table-column label="地震事件简称" align="center" prop="dedName">
                <template #default="scope"><span @click="detailDed(scope.row)" style="color:var(--el-color-primary);cursor:pointer">{{
                        scope.row.dedName
                }}</span></template>
            </el-table-column>
            <el-table-column label="发生时刻" align="center" prop="dedTime" />
            <el-table-column label="震中(宏观)" align="center" prop="dedMacroscopicEpicenter" />
            <el-table-column label="经度(°)" align="center" prop="dedLongitude" />
            <el-table-column label="纬度(°)" align="center" prop="dedLatitude" />
            <el-table-column label="震级" align="center" prop="dedEarthquake" />
            <el-table-column label="震源深度Km" align="center" prop="dedDepth" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="isAdminShow">
                <template #default="scope">
                    <el-button type="text" @click="handleUpdate(scope.row)">
                        修改</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
            @pagination="getList" />

        <!-- 添加弹出框 -->
        <el-dialog :title="title" v-model="open" append-to-body>
            <p class="dialogTitle">{{ title }}</p>
            <el-form ref="historyDisasterRef" :model="form" :rules="rules" label-width="150px" style="padding:0 40px 0px 20px">
                <el-form-item label="地震事件简称" prop="dedName">
                    <el-input v-model="form.dedName" placeholder="震中地名+震级值+“级地震”。例如，四川泸定6.8级地震" />
                </el-form-item>
                <el-form-item label="发生时刻" required>
                    <el-form-item prop="date">
                        <el-date-picker v-model="form.date" type="date" placeholder="YYYY-MM-DD"
                            value-format="YYYY-MM-DD" clearable />
                    </el-form-item>
                    <el-form-item prop="time" style="margin-left:10px">
                        <el-time-picker v-model="form.time" placeholder="HH:mm:ss" value-format="HH:mm:ss" clearable />
                    </el-form-item>
                </el-form-item>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="经度(°)" prop="dedLongitude">
                            <el-input v-model="form.dedLongitude" placeholder="请输入经度" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="纬度(°)" prop="dedLatitude">
                            <el-input v-model="form.dedLatitude" placeholder="请输入纬度" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="震级(级)" prop="dedEarthquake">
                            <el-input v-model="form.dedEarthquake" placeholder="请输入震级" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="参考位置" prop="dedLocation">
                            <el-input v-model="form.dedLocation" placeholder="请输入参考位置" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="震源深度(千米)" prop="dedDepth">
                            <el-input v-model="form.dedDepth" placeholder="请输入震源深度" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="最高烈度" prop="dedMaximumIntensity">
		                    <el-select v-model="form.dedMaximumIntensity" placeholder="请选择" clearable>
                                <el-option
                                    v-for="item in intensityList"
                                    :key="item.dictItemCode"
                                    :label="item.dictItemName"
                                    :value="item.dictItemCode"
                                />
		                    </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="震中(宏观)" prop="dedMacroscopicEpicenter">
                            <el-input v-model="form.dedMacroscopicEpicenter" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="死亡人数" prop="dedDeathToll">
                            <el-input v-model="form.dedDeathToll" placeholder="请输入死亡人数" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="死亡原因" prop="dedCauseOfDeath">
                            <el-input v-model="form.dedCauseOfDeath" placeholder="请输入死亡原因" type="textarea" :rows="5"
                                maxlength="500" show-word-limit />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="受伤人数" prop="dedNumberOfInjury">
                            <el-input v-model="form.dedNumberOfInjury" placeholder="请输入受伤人数" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="安置人数" prop="dedNumberOfPlacement">
                            <el-input v-model="form.dedNumberOfPlacement" placeholder="请输入安置人数" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="救援力量投入人数" prop="dedRescueForceInput">
                            <el-input v-model="form.dedRescueForceInput" placeholder="请输入救援力量投入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="医疗力量投入人数" prop="dedInputOfMedicalForce">
                            <el-input v-model="form.dedInputOfMedicalForce" placeholder="请输入医疗力量投入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="经济损失（亿元）" prop="dedEconomicLosses">
                            <el-input v-model="form.dedEconomicLosses" placeholder="请输入经济损失（亿元）" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="基础设施破坏情况" prop="dedInfrastructureDamage">
                    <el-input v-model="form.dedInfrastructureDamage" placeholder="请输入基础设施破坏情况" type="textarea" :rows="5"
                        maxlength="500" show-word-limit />
                </el-form-item>
                <el-form-item label="地质灾害情况" prop="dedGeologicalHazardSituation">
                    <el-input v-model="form.dedGeologicalHazardSituation" placeholder="请输入地质灾害情况" type="textarea"
                        :rows="5" maxlength="500" show-word-limit />
                </el-form-item>
                <el-form-item label="次生火灾" prop="dedSecondaryFire">
                    <el-input v-model="form.dedSecondaryFire" placeholder="请输入次生火灾" type="textarea" :rows="5"
                        maxlength="500" show-word-limit />
                </el-form-item>
                <el-form-item label="次生水灾" prop="dedSecondaryFlood">
                    <el-input v-model="form.dedSecondaryFlood" placeholder="请输入次生水灾" type="textarea" :rows="5"
                        maxlength="500" show-word-limit />
                </el-form-item>
                <el-form-item label="次生爆炸" prop="dedSecondaryExplosion">
                    <el-input v-model="form.dedSecondaryExplosion" placeholder="请输入次生爆炸" type="textarea" :rows="5"
                        maxlength="500" show-word-limit />
                </el-form-item>
                <el-form-item label="危化品泄漏" prop="dedDangerousChemicalLeak">
                    <el-input v-model="form.dedDangerousChemicalLeak" placeholder="请输入危化品泄漏" type="textarea" :rows="5"
                        maxlength="500" show-word-limit />
                </el-form-item>
                <el-form-item label="震害现象描述" prop="dedDisasterDescription">
                    <el-input v-model="form.dedDisasterDescription" placeholder="请输入震害现象描述" type="textarea" :rows="5"
                        maxlength="500" show-word-limit />
                </el-form-item>
                <el-form-item label="典型震害图片" prop="typicalEarthquakeDamagePicture">
		            <image-upload ref="dxzh" :disabled="!isEdit"  v-model="form.typicalEarthquakeDamagePicture"/>
                </el-form-item>
                <el-form-item label="等震线及烈度图" prop="isoseismalLineAndIntensityPicture">
		            <image-upload ref="dzxjld" :disabled="!isEdit"  v-model="form.isoseismalLineAndIntensityPicture"/>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="5"
                        maxlength="500" show-word-limit />
                </el-form-item>
                <el-form-item label="附件">
                    <file-upload ref="fileUpload" :disabled="!isEdit" v-model="form.enclosure" :limit="limit" />
                </el-form-item>
            </el-form>
            <!-- <el-table :data="form.fileList" stripe>
                <el-table-column label="附件名称" align="center" prop="" width="400px" show-overflow-tooltip />
                <el-table-column label="大小" align="center" prop="" />
                <el-table-column label="状态" align="center" prop="" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-button type="text" @click="deletAccessory(scope.row)">
                            删除</el-button>
                    </template>
                </el-table-column>
            </el-table> -->
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确定</el-button>
                    <el-button plain @click="cancel">取消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 查看弹出框 -->
        <el-dialog v-model="openDetail" title="查看历史地震灾害数据" width="900px" append-to-body>
            <p class="dialogTitle">查看历史地震灾害数据</p>
            <DetailHistoryDisaster :detilList="form" />
        </el-dialog>
        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
            <p></p>
            <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                :disabled="upload.isUploading" :before-upload="handleFileBeforeUpload"
                :on-progress="handleFileUploadProgress" :on-error="handleFileUploadError"
                :on-success="handleFileSuccess" :auto-upload="false" drag>
                <el-icon class="el-icon--upload">
                    <upload-filled />
                </el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                            @click="importTemplate('历史震害数据模板.xlsx')">下载模板</el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button plain @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
  
<script setup name="historyDisasterData">
import {positive2decimals,positive1decimals,positive4decimals,positiveInteger} from "@/utils/history.js"
import { getEarthquakeDisaster, updateEarthquakeDisaster, addEarthquakeDisaster, delEarthquakeDisaster, detailEarthquakeDisaster, isCouAdmin } from "@/api/basedatamanage/historyDisasterData.js"
import DetailHistoryDisaster from "./detailHistoryDisaster.vue"
import { getDict } from "@/api/system/dict";
import { getToken } from "@/utils/auth";
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const ids = ref();
const loading = ref(false);
const open = ref(false);
const openDetail = ref(false);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isEdit = ref(true);
const limit = ref(50);
const showSearch = ref(true);
const data = reactive({
    form: {
        dedName: undefined,
        dedTime: undefined,
        dedLongitude: undefined,
        dedLatitude: undefined,
        dedLocation: undefined,
        dedEarthquake: undefined,
        dedDepth: undefined,
        dedDeathToll: 0,
        dedCauseOfDeath: undefined,
        dedNumberOfInjury: 0,
        dedNumberOfPlacement: 0,
        dedRescueForceInput: 0,
        dedInputOfMedicalForce: 0,
        dedEconomicLosses: undefined,
        dedInfrastructureDamage: undefined,
        dedGeologicalHazardSituation: undefined,
        dedSecondaryFire: undefined,
        dedSecondaryFlood: undefined,
        dedSecondaryExplosion: undefined,
        dedDangerousChemicalLeak: undefined,
        date: undefined,
        time: undefined,
        fileList: undefined,
        dedMaximumIntensity: undefined,
        dedMacroscopicEpicenter: undefined,
        dedDisasterDescription: undefined,
        typicalEarthquakeDamagePicture: undefined,
        isoseismalLineAndIntensityPicture: undefined,
        remark: undefined,
    },
    queryParams: {
        page: 1,
        rows: 10,
        dedName: undefined,
        dedEarthquake: undefined,
        dedMacroscopicEpicenter: undefined,
        time:undefined,
        dedTime: undefined,
        endTime:undefined,
    },
    rules: {
        dedName: [{ required: true, message: "地震事件简称不能为空", trigger: "blur" }],
        date: [{ required: true, message: "发生日期不能为空", trigger: 'change' }],
        time: [{ required: true, message: "发生时间不能为空", trigger: 'change' }],
        dedLongitude: [{ required: true, message: '请输入正确的数值，保留两位小数', trigger: 'blur', validator: positive2decimals }],
        dedLatitude: [{ required: true, message: '请输入正确的数值，保留两位小数', trigger: 'blur', validator: positive2decimals }],
        dedLocation: [{ required: true, message: "参考位置不能为空", trigger: "blur" }],
        dedEarthquake: [{ required: true, message: '请输入正确的数值，保留一位小数', trigger: 'blur', validator: positive1decimals }],
        dedDepth: [{ required: true, message: '请输入正确的数值，保留一位小数', trigger: 'blur', validator: positive1decimals }],
        dedDeathToll: [{ required: true, message: '请输入整数值', trigger: 'blur', validator: positiveInteger }],
        dedMaximumIntensity:[{ required: true, message: "最高烈度不能为空", trigger: 'change' }],
        dedMacroscopicEpicenter: [{ required: true, message: "位置（宏观）不能为空", trigger: "blur" }],
        // dedCauseOfDeath: [{ required: true, message: "死亡原因不能为空", trigger: "blur" }],
        dedNumberOfInjury: [{ required: true, message: '请输入整数值', trigger: 'blur', validator: positiveInteger }],
        dedNumberOfPlacement: [{ required: true, message: '请输入整数值', trigger: 'blur', validator: positiveInteger }],
        dedRescueForceInput: [{ required: true, message: '请输入整数值', trigger: 'blur', validator: positiveInteger }],
        dedInputOfMedicalForce: [{ required: true, message: '请输入整数值', trigger: 'blur', validator: positiveInteger }],
        dedEconomicLosses: [{ required: true, message: '请输入正确的数值，保留四位小数', trigger: 'blur', validator: positive4decimals }],
        dedInfrastructureDamage: [{ required: true, message: "基础设施破坏情况不能为空", trigger: "blur" }],
        dedGeologicalHazardSituation: [{ required: true, message: "地质灾害情况不能为空", trigger: "blur" }],
        dedSecondaryFire: [{ required: true, message: "次生火灾不能为空", trigger: "blur" }],
        dedSecondaryFlood: [{ required: true, message: "次生水灾不能为空", trigger: "blur" }],
        dedSecondaryExplosion: [{ required: true, message: "次生爆炸不能为空", trigger: "blur" }],
        dedDangerousChemicalLeak: [{ required: true, message: "危化品泄漏不能为空", trigger: "blur" }],
        isoseismalLineAndIntensityPicture: [{ required: true, message: "等震线及烈度图不能为空", trigger: "change" }]
    },
    intensityList: []
})
const { queryParams, form, rules, intensityList } = toRefs(data)
/*** 导入参数 */
const upload = reactive({
    open: false,
    title: "",
    isUploading: false,
    headers: { token: "token " + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + "/fxfzypg/baseData/earthquakeDisasterImportExcel"
});
/** 打开导入表弹窗 */
function handleImport() {
    upload.title = "导入";
    upload.open = true;
}
// 模板下载
function importTemplate(name) {
    proxy.download("/base/product/downloadExcel", {
        fileName: name
    }, name);
};
/** 提交上传文件 */
function submitFileForm() {
    proxy.$refs["uploadRef"].submit();
};


/**文件上传前处理 */
function handleFileBeforeUpload(file) {
    proxy.$modal.loading("正在上传文件，请稍候...");
    return true
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
    proxy.$modal.closeLoading();
    proxy.$modal.msgError("上传文件失败");
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false;
    upload.isUploading = false;
    proxy.$modal.closeLoading();
    proxy.$refs["uploadRef"].handleRemove(file);
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.message + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
    getList();
};
// 获取烈度列表
function getIntensityList(){
    getDict("zgld").then(res => {
	    intensityList.value = res.data;
	});
}
getIntensityList()
/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.page = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    dataList.value = [];
    queryParams.value.dedTime = undefined;
    queryParams.value.endTime = undefined;
    proxy.resetForm("queryRef");
    handleQuery();
}

// 重置表单
function reset() {
    form.value = {
        dedName: undefined,
        dedTime: undefined,
        dedLongitude: undefined,
        dedLatitude: undefined,
        dedLocation: undefined,
        dedEarthquake: undefined,
        dedDepth: undefined,
        dedDeathToll: undefined,
        dedCauseOfDeath: undefined,
        dedNumberOfInjury: undefined,
        dedNumberOfPlacement: undefined,
        dedRescueForceInput: undefined,
        dedInputOfMedicalForce: undefined,
        dedEconomicLosses: undefined,
        dedInfrastructureDamage: undefined,
        dedGeologicalHazardSituation: undefined,
        dedSecondaryFire: undefined,
        dedSecondaryFlood: undefined,
        dedSecondaryExplosion: undefined,
        dedDangerousChemicalLeak: undefined,
        data: undefined,
        time: undefined,
        fileList: undefined,
        dedMaximumIntensity: undefined,
        dedMacroscopicEpicenter: undefined,
        dedDisasterDescription: undefined,
        typicalEarthquakeDamagePicture: undefined,
        isoseismalLineAndIntensityPicture: undefined,
        remark: undefined,
    }
    proxy.resetForm("historyDisasterRef");
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.dedId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 查询历史地震灾害数据列表 */
function getList() {
    loading.value = true;
    if(queryParams.value.time!=undefined){
        queryParams.value.dedTime = JSON.parse(JSON.stringify(queryParams.value.time))[0]
        queryParams.value.endTime = JSON.parse(JSON.stringify(queryParams.value.time))[1]
    }
    getEarthquakeDisaster(queryParams.value).then(response => {
        dataList.value = response.data.rows;
        total.value = response.data.total;
        loading.value = false;
    });
}

// 添加
function handleAdd() {
    title.value = "添加历史地震灾害数据"
    open.value = true;
    reset();
}

/** 删除按钮操作 */
function handleDelete(row) {
    const id = row.id || ids.value;
    proxy.$modal.confirm('是否确认删除勾选的历史地震灾害数据？').then(function () {
        return delEarthquakeDisaster(id);

    }).then((res) => {
        getList();
        proxy.$modal.msgSuccess(res.data);
    }).catch(() => { });
}

// 修改
function handleUpdate(row) {
    reset();
    isEdit.value = true;
    getDetail(row.dedId)
}
function getDetail(id) {
    detailEarthquakeDisaster(id).then(response => {
        form.value = response.data;
        form.value.date = form.value.dedTime.split(' ')[0];
        form.value.time = form.value.dedTime.split(' ')[1];
        if (isEdit.value) {
            open.value = true;
            title.value = "修改历史地震灾害数据"
        } else {
            openDetail.value = true;
        }
    })
}
/** 查看方法*/
function detailDed(row) {
    reset();
    isEdit.value = false;
    openDetail.value = true;
    getDetail(row.dedId)
}

//处理附件格式
function eachFiles(fileName) {
    let deepFile = JSON.parse(JSON.stringify(proxy.$refs[fileName].fileList))
    let Ids = []
    for(var i = 0; i < deepFile.length; i++) {
        Ids.push(deepFile[i].attachId)
    }
    return Ids.join(",");
}

/** 提交按钮 */
function submitForm() {
	form.value.enclosure = eachFiles('fileUpload');
	form.value.typicalEarthquakeDamagePicture = eachFiles('dxzh');
	form.value.isoseismalLineAndIntensityPicture = eachFiles('dzxjld');
    form.value.dedTime = form.value.date +' '+ form.value.time;
    proxy.$refs["historyDisasterRef"].validate(valid => {
        if (valid) {
            if (title.value!="添加历史地震灾害数据") {
                updateEarthquakeDisaster(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    proxy.resetForm("queryRef");
                    getList();
                });
            } else {
                addEarthquakeDisaster(form.value).then(response => {
                    proxy.$modal.msgSuccess("保存成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 取消按钮 */
function cancel() {
    open.value = false;
    reset();
}


/** 导出按钮操作 */
function handleExport() {
    proxy.download('/fxfzypg/baseData/earthquakeDisasterExportExcel', {
        ...queryParams.value
    }, `difference_${new Date().getTime()}.xls`)
}

// 权限
const isAdminShow = ref(false)
const isAdmin = () => {
  isCouAdmin().then(res => {
    const { code, data } = res
    if(code == 200){
      isAdminShow.value = (data.message == "是" ? true : false)
    }
  })
}

getList();
isAdmin()

</script>
  
<style lang="scss" scoped>
</style>